package com.webinsky.web.resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.webinsky.publish.domain.Info;
import com.webinsky.publish.domain.InfoFilter;
import com.webinsky.publish.domain.Infos;
import com.webinsky.publish.service.InfoManagement;
import com.webinsky.site.domain.Site;
import com.webinsky.site.service.SiteManagement;
import com.webinsky.web.data.InfoForm;
import com.webinsky.web.data.Response;

import reactor.core.publisher.Mono;

@Component
public class InfoResource {
	@Autowired
	private InfoManagement infoManagement;
	@Autowired
	private SiteManagement siteMangement;
	
	public Mono<ServerResponse> submitInfo(ServerRequest request){
		return request.bodyToMono(InfoForm.class).flatMap( data -> {
			Info info = new Info();
			info.setContent(data.content);
			info.setEmail(data.email);
			info.setInfoDate(data.infoDate);
			info.setMobile(data.mobile);
			info.setName(data.name);
			info.setSiteId(data.siteId);
			info.setAddress(data.address);
			info.setCompany(data.company);
			info.setRemark(data.remark);
			Site site = siteMangement.load(data.siteId);
			if ( site != null ) {
				info.setSiteName(site.getSiteName());
				infoManagement.submitInfo(info);
			}
			return ServerResponse.ok().syncBody(Response.create(info.getId(), Response.STATUS_OK, ""));
		});
	}
	
	public Mono<ServerResponse> queryInfosByFilter(ServerRequest request){
		return request.bodyToMono(com.webinsky.web.data.InfoFilter.class).flatMap( data -> {
			InfoFilter filter = new InfoFilter();
			filter.setEmail(data.email);
			filter.setInfoDateEnd(data.infoEnd);
			filter.setInfoDateStart(data.infoStart);
			filter.setMobile(data.mobile);
			filter.setName(data.name);
			filter.setSiteId(data.siteId);
			filter.setContent(data.infoContent);
			filter.setStart(data.pageStart);
			filter.setSize(data.pageSize);
			Infos infos = infoManagement.getByFilter(filter);
			return ServerResponse.ok().syncBody(Response.create(infos, Response.STATUS_OK, ""));
		});
	}
	
	
	
	public Mono<ServerResponse> deleteInfo(ServerRequest request) {
		String id = request.pathVariable("id");
		if ( id != null  ) {
			infoManagement.deleteInfo(Integer.valueOf(id));
			return ServerResponse.ok().syncBody(Response.create("", Response.STATUS_OK, ""));
		}
		return ServerResponse.ok().syncBody(Response.create("", Response.STATUS_WRONGARUGS_ERROR, "参数错误"));
	}
	
}
